package com.esionet.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.esionet.common.api.annotation.IgnoreAuth;
import com.esionet.common.utils.HttpUtils;
import com.esionet.common.utils.IPUtils;
import com.esionet.common.utils.bean.R;
import com.esionet.entity.Account;
import com.esionet.entity.dto.AccountDto;
import com.esionet.entity.dto.WxLoginDto;
import com.esionet.service.AccountService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.UUID;


/**
 * 前端接口-登陆模块
 *
 * @author chenxuan
 */
@RestController
@RequestMapping("/api/")
@Api(tags = "微信小程序-登陆模块")
public class ApiLoginController {

    @Autowired
    private AccountService accountService;

    @Value("${wx.appId}")
    private String WX_APP_ID;
    @Value("${wx.secret}")
    private String WX_SECRET;
    /**
     * 微信小程序-登录
     */
    @IgnoreAuth
    @PostMapping("wxLogin")
    @ApiOperation(value = "用户登陆", notes = "用户登陆")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "code", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "nickName", value = "nickName", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "avatarUrl", value = "avatarUrl", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "gender", value = "gender", required = true, dataType = "int", paramType = "query"),
    })
    public R wxLogin(@RequestBody WxLoginDto wxLoginDto, HttpServletRequest request) {
        //获取openId
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="
                + WX_APP_ID + "&secret=" + WX_SECRET + "&js_code=" + wxLoginDto.getCode() + "&grant_type=authorization_code";
        String res = HttpUtils.sendPost(url);
        JSONObject jsonObject = JSONObject.parseObject(res);
        if (jsonObject.get("errcode") != null) {
            return R.error("用户认证失败");
        }
        String openId = jsonObject.get("openid").toString();
        try{
            String ip = IPUtils.getIpAddr(request);

            AccountDto accountDto = accountService.findByLoginName(openId);

            String token;
            if(accountDto == null){
                //注册账号
                token =  accountService.wxRegister(wxLoginDto,openId,ip);
            }else{
                //刷新token
                token = UUID.randomUUID().toString();
                Account account = accountService.get(accountDto.getId());
                account.setToken(token);
                account.setLastLoginIp(ip);
                account.setLastLoginTime(new Date());
                accountService.update(account);
            }

            return R.ok().put("token",token);
        }catch (Exception e){
            return R.error("微信信息获取失败!");
        }
    }


}
